package locks.dead.resources;

import java.util.concurrent.Semaphore;

/**
 * 资源竞争死锁
 */
public class Compete {
    //A数据库连接池
    private static Semaphore aDataBaseConnectPoll = new Semaphore(2);
    //B数据库连接池
    private static Semaphore bDataBaseConnectPoll = new Semaphore(2);

    public static void main(String[] args) throws Exception {
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                try {
                    aDataBaseConnectPoll.acquire();
                    try {
                        bDataBaseConnectPoll.acquire();


                    } catch (Exception e) {
                    } finally {
                        bDataBaseConnectPoll.release();
                    }
                } catch (Exception e) {
                } finally {
                    aDataBaseConnectPoll.release();
                }
            }
        });


        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                try {
                    bDataBaseConnectPoll.acquire();
                    try {
                        aDataBaseConnectPoll.acquire();


                    } catch (Exception e) {
                    } finally {
                        aDataBaseConnectPoll.release();
                    }
                } catch (Exception e) {
                } finally {
                    bDataBaseConnectPoll.release();
                }
            }
        });

        //肯能因为资源问题导致死锁
        thread1.start();
        thread2.start();
    }


}
